﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using UnityEngine;

class ClusterBomb : MissileFunction
{
    public GameObject m_SubFlyItem = null;
    public int m_SubFlyNumber = 3;
    bool m_HasSubFlyItem = true; 
    override public void InitParameter(Vector3 position, Vector3 direction, float flyVelocity, float range, float damge, string weaponClassName, Weapon.DamageType dameageType, Ship ship, Weapon weapon)
    {
        base.InitParameter(position, direction, flyVelocity, range, damge, weaponClassName, dameageType, ship, weapon);
        m_HasSubFlyItem = true;
    }
    public override void Update()
    {
        base.Update();
        if (UtilsGame.IsOnline() && !UtilsGame.IsServer(gameObject))
        {
            return;
        }
        if(Life < 8 && m_HasSubFlyItem) 
        {
            FreeSons();
            m_HasSubFlyItem = false;
            OnBoom();
        }
    }

    public void FreeSons()
    {
        var horizontalDir = Vector3.Cross(FlyDirection, new Vector3(0, 0, 1));
        var offset = horizontalDir * 0.4f;

        Ship ship = null;
        if(m_Ship)
            ship = m_Ship.GetComponent<Ship>();
        for (int i=0; i<m_SubFlyNumber; ++i)
        {
            var subFlyitem = Instantiate(m_SubFlyItem);
            var flyItem = subFlyitem.GetComponent<FlyItem>();
            if(flyItem)
            {
                float process = (i / (float)m_SubFlyNumber);

                flyItem.InitParameter(transform.position + offset * (i - m_SubFlyNumber / 2),
                    Quaternion.AngleAxis(process * 40 - 20, new Vector3(0,0,1)) * FlyDirection,
                    FlyVelocity * 1.4f, 
                    Life, 
                    Damage / m_SubFlyNumber, 
                    "",
                    WeaponType,
                    ship, 
                    null);
                flyItem.FlyVelocity = FlyVelocity;
            }
        }
    }
}
